<?php  
/*
Контроллер модуля. 

Унаследован от шаблона контроллеров модулей 
Вызывает свою модель 
Вызывает свое представление

Генерит хтмл или ошибку 
*/
 
 
// контроллер вызывает модель, затем представление 
// и формирует output, а также массив входных данных для виджетов array('widget_descriptor'=>array('param_name'=>param_value)) 
 
 
class MebelModul extends BasicModulController implements BasicModulControllerInterface {
// контроллер модуля

  

   // private $widget_inputdata_arr; // перенести в интерфейс BasicModulController

    /*
    function __construct($registry = null){
      
      $this->registry = $registry; 
       
      parent::__construct(); 
      
       $this->modul_id = $this->getModulIdByIndex(MODUL_INDEX);

      if(isset($this->registry) AND ($this->registry->get('virtual_modul_index')) != '')
         $this->life_modul_index = $this->registry->get('virtual_modul_index'); 
      elseif(isset($this->registry) AND ($this->registry->get('modul_index')) != '')   
        $this->life_modul_index = $this->registry->get('modul_index'); 
       
      if(!is_object($this->registry)) if($this->registry != null) {} 
      else $this->registry = registry::getInstance();  
       

      $this->modul_index = $this->registry->get('modul_index'); // 'Mebel'
       
      // виджеты 
      //$this->widget_enter_data = array();
      //$this->widget_enter_data['widget'] = array('1'=>'a'); //var_dump($this->widget_enter_data);
      
      // инициализация модели
      $this->model = new $this->modul_index;
      
      // инициализация представления
      $classname_view = $this->modul_index."View";
      $ModulView = new $classname_view( $this->modul_id);
      $this->global_view = $ModulView->getView(); // глобальное представление
      $this->view = $ModulView; // представление модуля
      
      // установка переменных, полученных из модели
      //$this->view->Set('asd',1234);
      
      self::$instance = $this;
      
      // генерация html
      // [!] закоментить после запуска Фабрики
      //$this->html = $this->view->render();
      
      
    } // -- __construct
    */

    /*
    function getHtml(){
        return $this->html;
    }

    // [!] сделать, чтобы рендерился шаблон модуля и шаблон отдельно главный
    // попробовать взять смарти из реестра или создать второй объект
    */



    /*
    public static function getInstance(){
        // [!] метод обязателен для каждого модуля
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className;
        }

        return self::$instance;
    } // --

    static function action(){

        $obj = static::getInstance();
        $method = $obj->action;

        if( !method_exists($obj, $method) ) throw new Exception('No action exists');

        $obj->$method();

    } // --

    //
    public static function getView(){
        $obj = static::getInstance();
        return $obj->view;
    }
    */
    // -------- Mebel [origin] точка входа ----------
    function actionMebelBasic(){

    } // --
    
    // -------- dining [virtual] точка входа ----------
    function actionDiningBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # TEST events
        $onCellSelect = "
            function (rowid, iCol, cellContent, e) {alert('23')
                        grid.restoreRow(lastSelection);
                        grid.editRow(rowid, true, null, null, null, null, null);
                        lastSelection = rowid;
                        }
        ";
        $loadCompleteAction = 'function(request)
       {
         jQuery("#photo_dining_grid").setCaption("gridcaption");
       }';

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'loadComplete' =>  new Zend\Json\Expr($loadCompleteAction),
            'navoptions' => array('edit', /*'search'*/),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);


        // test
       //$photo_grid->setGridParameter('loadComplete', new Zend\Json\Expr($loadCompleteAction));

        $photo_grid->_populate();

        // [!] Можно подключать так
        /*
        $code = "

             function multisave(e){

                        var grid_name = 'photo_dining_grid'
                        var url = 'http://admin.remontik.kh.ua/dining/multisave'
                        var data = 'save'

                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: data,
                            success: function(dat){
                                jQuery('#' + grid_name).trigger('reloadGrid');
                                $('.multiload-box').html('');
                            },
                dataType: 'json'
                });

                }
        ";

        $code_dynamic = "

            $('button[name=valim_optom]').on('click',multisave);

        ";

        Controller::appendHeadCode($code);
        Controller::appendHeadCodeDynamic($code_dynamic);
        */

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // -- 

    // -------- chamber [virtual] точка входа ----------
    function actionChamberBasic(){
        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // --
    
    // -------- wardrobe [virtual] точка входа ----------
    function actionWardrobeBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // --

    function actionDiningGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionChamberGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionWardrobeGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    private function _editcell(){
        $result = true;

        $id = $this->registry->request->postParam('id') ;
        $oper = $this->registry->request->postParam('oper') ;
        $sort = $this->registry->request->postParam('sort') ;
        $text = $this->registry->request->postParam('text') ;
        $title = $this->registry->request->postParam('title') ;

        $data = array(
            "title" => $title,
            "text" => $text,
            "sort" => $sort,
        );

        $entity = 'photo';
        $model_name = ucfirst($entity) . "Model";
        $model = new $model_name('photo_id', $id);
        $data_exists = $model->getData();


        if(isset($data_exists[0])){
            $data = array_merge($data_exists[0],$data );
        }

        $data = array(0 => $data);

        $model->setData($data);

        $model->Flush();

        return $result;
    }

    private function editCellAll(){
        $this->setNoRender();

        $status = '';

        if( ($res = $this->_editcell()) === true){
            $status = 'ok';
        }

        $this->json($data = array('responsestatus' => $status));
    }

    function actionDiningEditcell(){
        $this->editCellAll();
    }

    function actionChamberEditcell(){
        $this->editCellAll();
    }

    function actionWardrobeEditcell(){
        $this->editCellAll();
    }

    function actionDiningДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    function actionChamberДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    function actionWardrobeДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    private function insertPhoto($unit = null){
        # Залить фото
        $pk = false;

        $filename = $_FILES['photo']['name'];
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = md5($rnd_val . $unit . rand());
        $rnd_val = substr($rnd_val,0,8);

        $link = $rnd_val . ".jpg";

        $local_path = "tmp/";
        $file_1 = $link; //$filename;
        $file_1_up = $file_1;
        $file_1 = PUBLIC_PATH . "/tmp/$file_1";;
        $file_2 = 'sm_'.$link;
        $file_2_up = $file_2;
        $file_2 = PUBLIC_PATH . "/tmp/$file_2";

        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_1,900,600);
        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_2,300,200);

        if($this->model->uploadImage($file_1_up, $unit)){
            $this->model->uploadImage($file_2_up, $unit);
        }

        @unlink($file_1);
        @unlink($file_2);

        # Записать в базу
        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = substr($rnd_val,0,8);

        $link = "{$this->registry->virtual_modul_id}_{$rnd_val}" . substr($file_1_up,0,-5);

        $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
                      'date_added' => date("Y-m-d H:i:s"),
                      'title' => '',
                      'text' => '',
                      'link' => $file_1_up,
                      'sort' => 100,
        );

        $PhotoModel = new PhotoModel();
        $pk = $PhotoModel->Set($data);

        return $pk;
    }

    /*
     * [универсальный] метод загрузки файлов с сервера на ftp
     */
    private function imageToFtp(array $photo_arr, $unit){



        $result = true;

        foreach($photo_arr as $k => $v){

            $pk = false;
            $local_path = $v;

            $link = md5(rand() . date("H:i:s"));
            $link = md5($link . $unit . rand());
            $link = substr($link,0,8);
            $link = $link . ".jpg";





            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/$link",900,600);
            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/sm_" . $link,300,200);

            $this->model->openFtpConnection();

            $this->model->putRemoteFile($link, PUBLIC_PATH . "/tmp", null, $unit, true);
            $this->model->putRemoteFile("sm_$link", PUBLIC_PATH . "/tmp", null, $unit, true);


            @unlink($local_path);
            @unlink(PUBLIC_PATH . "/tmp/$link");
            @unlink(PUBLIC_PATH . "/tmp/sm_" . $link);

            $this->model->closeFtpConnection();


            # Записать в базу
            $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
                          'date_added' => date("Y-m-d H:i:s"),
                          'title' => '',
                          'text' => '',
                          'link' => $link,
                          'sort' => 100,
            );

            $PhotoModel = new PhotoModel();
            $pk = $PhotoModel->Set($data);

        }


        return $result;

    }

    function actionDiningMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }

    function actionChamberMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }

    function actionWardrobeMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }














}